package dln.stat;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.bat.pt.BObj;
import net.bat.util.Cfg;
import net.sf.jxls.exception.ParsePropertyException;
import net.sf.jxls.transformer.XLSTransformer;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.joda.time.DateTime;

import dln.stat.ds.BxmidleDataSource;
import dln.stat.ds.InstituteDataSource;
import dln.stat.ds.StaBxmidleDataSource;

public class StactisticHandler extends HttpServlet {
	public static final char STATISTIC_DEPARTMENT = 'D'; // 部门统计

	public static final char STATISTIC__INSTITUTE = 'I';// 全院统计

	public static final char STATISTIC_AGE = 'A'; // 年龄段统计

	public static final char STATISTIC_MONTH = 'M'; // 按月统计
	
	public static final char STATISTIC_JHSY = 'J'; //计划生育
	
	public static final char STATISTIC_DBYW = 'Y'; //大病医疗药物
	
	public static final char STATISTIC_DBQX= 'Q'; //大病器械
	
	public static final char STATISTIC_PTMZ= 'P'; //普通用户门诊
	
	public static final char STATISTIC_PTZY= 'Z'; //普通用户住院
	
	public static final char STATISTIC_PTJS= 'S'; //普通用户计划生育
	
	private static final long serialVersionUID = 1L;
	
    private static final String CONTENT_TYPE = "application/vnd.ms-excel;charset=UTF-8";
    
	private static final String DATE_FORMAT = "yyyy-MM-dd-hh-mm-ss";
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ExcelExportor ee = Cfg.getContext().getBean("ExcelExportor",
				ExcelExportor.class);		
		File file = ee.buildDestPath();
		char type = request.getParameter("type").charAt(0);
		String start = request.getParameter("start");
		String end = request.getParameter("end");
        Map<String, List<?>> beanParams = new HashMap<String, List<?>>();	
        StaBxmidleDataSource ds;
        BxmidleDataSource bds =new BxmidleDataSource("dln.stat.querySingleTypeStat");
        Integer uid = 0;
        if(request.getParameter("uid")!=null){
    		uid =Integer.parseInt(request.getParameter("uid"));//add null check
        }
		//String bxtype = request.getParameter("bxtype");
		// 输出文件流
		switch (type) {
			case STATISTIC_DEPARTMENT:        
		        ds = new StaBxmidleDataSource("dln.stat.queryDptStat");
				ds.generate(new DateTime(start).toDate(), new DateTime(end).toDate());
				beanParams.put("depts", ds.getResult());	
		        createExcelFile(ExcelTemplateFiles.BM.getCN(), file.getAbsolutePath(), beanParams);  
		        break;
			case STATISTIC__INSTITUTE:
		        ds = new InstituteDataSource("dln.stat.queryInsStat");
				ds.generate(new DateTime(start).toDate(), new DateTime(end).toDate());
				beanParams.put("ins", ds.getResult());
				createExcelFile(ExcelTemplateFiles.QY.getCN(), file.getAbsolutePath(), beanParams); 
				break;
			case STATISTIC_AGE:       
				ds = new StaBxmidleDataSource("dln.stat.queryAgeStat1");
				ds.generate(new DateTime(start).toDate(), new DateTime(end).toDate());
				beanParams.put("ages", ds.getResult());
				ds = new StaBxmidleDataSource("dln.stat.queryAgeStat2");
				ds.generate(new DateTime(start).toDate(), new DateTime(end).toDate());
				beanParams.put("ages2", ds.getResult());				
		        createExcelFile(ExcelTemplateFiles.NLD.getCN(), file.getAbsolutePath(), beanParams); 
		        break;
			case STATISTIC_MONTH:        
		        ds = new StaBxmidleDataSource("dln.stat.queryMonthStat");
				ds.generate(new DateTime(start).toDate(), new DateTime(end).toDate());
				beanParams.put("months", ds.getResult());	
		        createExcelFile(ExcelTemplateFiles.MONTH.getCN(), file.getAbsolutePath(), beanParams); 
		        break;
			case STATISTIC_JHSY:   
				bds.generate(BxmidleCatalog.JHSY.getCN(),new DateTime(start).toDate(), new DateTime(end).toDate());
				beanParams.put("types", bds.getResult());
				createExcelFile(ExcelTemplateFiles.JHSY.getCN(), file.getAbsolutePath(), beanParams); 
				break;
			case STATISTIC_DBYW:   
				bds.generate(BxmidleCatalog.DBYL_YW.getCN(),new DateTime(start).toDate(), new DateTime(end).toDate());
				beanParams.put("types", bds.getResult());
				createExcelFile(ExcelTemplateFiles.DBYL_YW.getCN(), file.getAbsolutePath(), beanParams); 
				break;
			case STATISTIC_DBQX:   
				bds.generate(BxmidleCatalog.DBYL_QX.getCN(),new DateTime(start).toDate(), new DateTime(end).toDate());
				beanParams.put("types", bds.getResult());
				createExcelFile(ExcelTemplateFiles.DBYL_QX.getCN(), file.getAbsolutePath(), beanParams); 
				break;
			case STATISTIC_PTMZ: 
				bds =new BxmidleDataSource("dln.stat.queryUserSingleTypeStat");
				bds.generate(BxmidleCatalog.MZ.getCN(),new DateTime(start).toDate(), new DateTime(end).toDate(),uid);
				beanParams.put("types", bds.getResult());
				createExcelFile(ExcelTemplateFiles.PTYH_MZ.getCN(), file.getAbsolutePath(), beanParams); 
				break;
			case STATISTIC_PTZY:  
				bds =new BxmidleDataSource("dln.stat.queryUserSingleTypeStat");
				bds.generate(BxmidleCatalog.ZY.getCN(),new DateTime(start).toDate(), new DateTime(end).toDate(),uid);
				beanParams.put("types", bds.getResult());
				createExcelFile(ExcelTemplateFiles.PTYH_ZY.getCN(), file.getAbsolutePath(), beanParams); 
				break;
			case STATISTIC_PTJS:
				bds =new BxmidleDataSource("dln.stat.queryUserSingleTypeStat");
				bds.generate(BxmidleCatalog.JHSY.getCN(),new DateTime(start).toDate(), new DateTime(end).toDate(),uid);
				beanParams.put("types", bds.getResult());
				createExcelFile(ExcelTemplateFiles.PTYH_JHSY.getCN(), file.getAbsolutePath(), beanParams); 
				break;
			default:
				break;
			// pss,UMService.getUserBySession(request));
		}
		response.setContentType(CONTENT_TYPE);
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
		String filename = sdf.format(Calendar.getInstance().getTime())
				.toString() + "_obj.xls"; // 2010-03-03:02:43:39_obj.xls
		response.setHeader("Content-Disposition", "attachment;filename="
				+ filename);
		OutputStream out = response.getOutputStream(); // 将 WritableWorkbook
		ee.exportExcel(out);
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			doGet(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@SuppressWarnings("rawtypes")
	public static void createExcelFile(String tplPath, String destPath, Map beanParams) {
        XLSTransformer former = new XLSTransformer();
        try {
            former.transformXLS(tplPath, beanParams, destPath);
        } catch (ParsePropertyException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
}
